#include "MemDB.h"


#include "Table.h"
#include "TableOrder.h"
#include "Util.h"


MemDB::MemDB()
{
}
MemDB::~MemDB()
{
}

int MemDB::insertTable(Table * table){
    if(table != nullptr) return -1;
    auto iter = tables.find(table->getName());
    if(iter == tables.end()){
        tables.insert(std::make_pair(table->getName(), table));
        return 0;
    }
    return -1;
}
int MemDB::removeTable(const std::string & name){
    auto iter = tables.find(name);
    if(iter != tables.end()){
        tables.erase(iter);
    }
    return 0;
}
int MemDB::init(){
    insertTable(new TableOrder());
    return 0;
}
void MemDB::deinit(){
    auto it = tables.begin();
    for(; it != tables.end(); ++it){
        delete it->second;
    }
    tables.clear();
}

Table * MemDB::getTable(const std::string & tableName) const {
    auto iter = tables.find(tableName);
    return (iter != tables.end()) ?  iter->second:nullptr;
}






void MemDB::test(){
    MemDB db;
    db.init();

    auto order = db.getTable("order");
    order->insert(1, Util::make("value"));
    order->update(1, Util::make("value2"));
    order->remove(1);

    order->insert(1, Util::make("value1"));
    order->insert(2, Util::make("value2"));
    order->insert(3, Util::make("value3"));
    order->insert(4, Util::make("value4"));
    order->insert(5, Util::make("value5"));

    auto value = order->find(1);
    std::cout << "value:"  << value << std::endl;

    auto records = order->rangeScan(3, 2, true, "pk");
    std::cout << "records:" << records->toString() << std::endl;

    db.deinit();
}
